const { removeImg } = require('../utils/removeFiles-handle');

const productsService = require('../service/products.service');

class ProductController {
  // 通过名称获取商品信息
  async getProductInformationByName(ctx, next) {
    const {name} = ctx.query;

    const result = await productsService.getProductInformationByName(name);

    ctx.body = result;
  }
  
  // 获取商品信息
  async getProductInformationByLimit(ctx, next) {
    const {offset, size} = ctx.query;

    const result = await productsService.getProductInformationByLimit(offset, size);

    ctx.body = result;
  }

  // 添加商品数据
  async addProductInformation(ctx, next) {
    const {name, price, introduce, details} = ctx.req.body;
    const {filename} = ctx.req.file;
    
    const imagePatch = `${APP_HOST}:${APP_PORT}/upload/getImgByPath/${filename}`;
    
    // 验证商品是否存在
    const checkExist = await productsService.getProductInformationByName(name);

    if (checkExist.length) {
      removeImg(filename);
      ctx.body = '商品名称已存在，请重新添加';

      return;
    } else {
      const result = await productsService.addProductInformation(name, price, introduce, details, imagePatch);
      ctx.body = result;
    }
  }

  // 修改商品信息
  async changeProductInformation(ctx, next) {
    const {id, name, price} = ctx.query;
    
    // 验证商品是否存在
    const checkExist = await productsService.getProductInformationByName(name);

    if (checkExist.length) {
      ctx.body = '商品名称已存在，请重新添加'

      return;
    } else {
      const result = await productsService.changeProductInformation(id, name, price);
      ctx.body = result;
    }
  }

  // 删除商品信息
  async deleteProductInformation(ctx, next) {
    const {id, imagePatch} = ctx.query;
    
    const transformImg = imagePatch.split('/');
    const beforeImagePatch = transformImg[transformImg.length - 1];

    const result = await productsService.deleteProductInformation(id, beforeImagePatch);

    ctx.body = result;
  }
}

module.exports = new ProductController();